<template>
  <panel title="数据字典">
    <a-layout id="components-layout-demo-top-side">
      <a-layout-content>
        <a-layout id="stemDictionary" style="padding: 0; background: #fff">
          <a-layout-sider width="240" style="background: #fff">
            <br />
            <selectTree
              v-if="loadTree"
              @selectedKey="selectedKey"
              :data="selectTreeData"
              :key="treeKey"
            ></selectTree>
          </a-layout-sider>
          <a-layout-content :style="{ padding: '0 24px', minHeight: '280px' }">
            <br />
            <a-form
              ref="ruleForm"
              :model="dictForm"
              :rules="rules"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-form-item label="名称" name="name">
                <a-input
                  placeholder="请输入名称"
                  v-model:value="dictForm.name"
                />
              </a-form-item>
              <a-form-item label="上级" name="pid" v-show="hiddenFlag">
                <inputTree
                  v-if="loadTree"
                  v-model:value="dictForm.pid"
                  :data="inputTreeData"
                ></inputTree>
              </a-form-item>
              <a-form-item name="code" label="编号">
                <a-input
                  placeholder="请输入编号"
                  v-model:value="dictForm.code"
                />
              </a-form-item>
              <a-form-item name="value" label="值">
                <a-input
                  placeholder="请输入值"
                  v-model:value="dictForm.value"
                />
              </a-form-item>
              <a-form-item name="json" label="辅助内容">
                <a-input
                  placeholder="请输入辅助内容"
                  v-model:value="dictForm.json"
                  type="textarea"
                />
              </a-form-item>
              <a-form-item name="note" label="备注">
                <a-textarea
                  placeholder="请输入备注"
                  :rows="4"
                  v-model:value="dictForm.note"
                />
              </a-form-item>
              <a-form-item :wrapper-col="{ span: 15, offset: 2 }">
                <a-button
                  type="primary"
                  style="margin-left: 20%"
                  :disabled="selectId === null"
                  @click="save"
                >
                  保存
                </a-button>
                <a-button
                  style="margin-left: 10px"
                  @click="addChild"
                  v-show="hiddenFlag"
                  :disabled="selectId === null"
                >
                  添加子项
                </a-button>
                <a-button
                  style="margin-left: 10px"
                  @click="deleteItem"
                  v-show="hiddenFlag"
                  :disabled="selectId === null"
                >
                  删除
                </a-button>
                <a-button
                  style="margin-left: 10px"
                  @click="hiddenFlag = true"
                  v-show="!hiddenFlag"
                >
                  返回
                </a-button>
              </a-form-item>
            </a-form>
            <br />
          </a-layout-content>
        </a-layout>
      </a-layout-content>
    </a-layout>
  </panel>
</template>
<script>
  import {
    GetMap,
    GetDictByPid,
    Add,
    Delete,
    Update,
  } from '@/api/dictionary/api'
  import selectTree from '@/mycomponents/selectTree/selectTree'
  import inputTree from '@/mycomponents/inputTree/inputTree'
  import panel from '@/plugins/panel/Panel.vue'
  import { ref } from 'vue'
  export default {
    components: {
      selectTree,
      inputTree,
      panel,
    },
    setup() {
      const ruleForm = ref()
      return {
        ruleForm,
      }
    },
    data() {
      return {
        loadTree: false, // 控制请求完成后加载树
        hiddenFlag: true, //控制按钮组
        treeKey: '', // 左侧树key
        selectTreeData: [], // 左侧树数据
        inputTreeData: [], // 右侧树数据
        selectId: null, //左侧选中节点的ID
        dictForm: {
          name: '',
          code: '',
          value: null,
          json: null,
          note: null,
          pid: null,
        },
        rules: {
          name: [
            {
              required: true,
              message: '请输入名称',
              trigger: 'blur',
              type: 'string',
            },
          ],
          pid: [
            {
              required: true,
              message: '请选择上级',
              trigger: 'change',
              type: 'string',
            },
          ],
          code: [
            {
              required: true,
              message: '请输入编号',
              trigger: 'blur',
              type: 'string',
            },
          ],
          value: [
            {
              required: true,
              message: '请输入值',
              trigger: 'blur',
              type: 'string',
            },
          ],
        },
      }
    },
    created() {
      this.load()
    },
    methods: {
      load() {
        var that = this
        that.selectTreeData = []
        that.inputTreeData = []
        GetDictByPid({
          bChild: true,
        }).then((res) => {
          console.log(res)
          if (res.isSuccess) {
            res.content.forEach((element) => {
              this.inputTreeData.push({
                title: element.name,
                id: element.id,
                value: element.id,
                isLeaf: element.count === 0,
              })
              that.selectTreeData.push({
                title: element.name,
                key: element.id,
                isLeaf: element.count === 0,
              })
            })
            that.loadTree = true
          }
        })
      },

      save() {
        //修改/保留字典数据
        this.ruleForm.validate().then(() => {
          if (!this.hiddenFlag) {
            Add({ isNameRepeat: true, isCodeRepeat: true }, this.dictForm).then(
              (res) => {
                if (res.isSuccess) {
                  this.treeKey = new Date().getTime() // 刷新selectTree（需修改）
                  this.$message.success('恭喜你，添加成功')
                } else {
                  console.log('错误', res)
                  this.$message.error(res.message)
                }
              }
            )
          } else {
            Update(
              { id: this.selectId, isNameRepeat: true, isCodeRepeat: true },
              this.dictForm
            ).then((res) => {
              console.log(res)
              if (res.isSuccess) {
                this.treeKey = new Date().getTime() // 刷新selectTree（需修改）
                this.$message.success('恭喜你，修改成功')
              } else {
                console.log('错误', res)
                this.$message.error(res.message)
              }
            })
          }
        })
      },
      // 添加子项
      addChild() {
        this.hiddenFlag = false
        // this.dictForm={}
        this.dictForm = {
          name: '',
          code: '',
          value: null,
          json: null,
          note: null,
          pid: this.selectId,
        }
      },
      //删除
      deleteItem() {
        Delete({ id: this.selectId }).then((res) => {
          if (res.isSuccess) {
            this.$message.success('恭喜你，删除成功')
            this.treeKey = new Date().getTime() // 刷新selectTree（需修改）
            this.selectId = null
            this.dictForm = {}
          } else {
            this.$message.error('删除失败')
          }
        })
      },
      selectedKey(childValue) {
        // childValue就是子组件传过来的值
        this.selectId = childValue
        GetMap({
          id: childValue,
        }).then((res) => {
          // console.log('===res=====', res)
          this.hiddenFlag = true
          this.dictForm.name = res.content.name
          this.dictForm.code = res.content.code
          this.dictForm.value = res.content.value
          this.dictForm.json = res.content.json
          this.dictForm.note = res.content.note
          this.dictForm.pid = res.content.pid
        })
      },
    },
  }
</script>
<style>
  #components-layout-demo-top-side .logo {
    width: 120px;
    height: 31px;
    background: rgba(255, 255, 255, 0.2);
    margin: 16px 28px 16px 0;
    float: left;
  }

  #stemDictionary .ant-layout-sider-children {
    border-right: 1px solid #B6c2c9;
  }
  #stemDictionary  .ant-tree-icon-hide {
    margin-left: 15% !important;
  }
</style>
